//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, Descriptions, List, message, Modal, Popover, Space } from "antd";
import { useStores } from "@/hooks";
import type { SimpleReviewInfo } from "@/api/project_review";
import {
    get as get_review, list_simple as list_simple_review, remove as remove_review,
    REVIEW_TYPE_BUG, REVIEW_TYPE_CODE, REVIEW_TYPE_FLOW, REVIEW_TYPE_MONTH, REVIEW_TYPE_PRODUCT, REVIEW_TYPE_QUARTER, REVIEW_TYPE_TEST,

} from "@/api/project_review";
import { request } from "@/utils/request";
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';
import { DeleteOutlined, EditOutlined, MoreOutlined } from "@ant-design/icons";
import EditReviewModal from "./components/EditReviewModal";
import UserPhoto from "@/components/Portrait/UserPhoto";
import moment from "moment";
import { useTranslation } from "react-i18next";


interface ReviewCardProps {
    reviewInfo: SimpleReviewInfo;
}

const ReviewCard = observer((props: ReviewCardProps) => {
    const { t } = useTranslation();

    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');
    const memberStore = useStores('memberStore');

    const [showUpdateModal, setShowUpdateModal] = useState(false);
    const [showRemoveModal, setShowRemoveModal] = useState(false);

    const removeReview = async () => {
        await request(remove_review({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            review_id: props.reviewInfo.review_id,
        }));
        message.info(t("text.removeSuccess"));
        setShowRemoveModal(false);
    };

    return (
        <Card title={<a style={{ fontSize: "20px", fontWeight: 700 }} onClick={e => {
            e.stopPropagation();
            e.preventDefault();
            projectStore.curReview = props.reviewInfo;
        }}>{props.reviewInfo.title}</a>}
            headStyle={{ backgroundColor: "#eee" }} bordered={false}
            bodyStyle={{ padding: "0px 0px" }}
            extra={
                <>
                    {projectStore.isAdmin && !projectStore.isClosed && (
                        <Space>
                            <Button type="link" icon={<EditOutlined />} title={t("text.edit")}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowUpdateModal(true);
                                }} />
                            <Popover placement="bottom" trigger="click" content={
                                <Space direction="vertical">
                                    <Button type="link" icon={<DeleteOutlined />} danger
                                        onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setShowRemoveModal(true);
                                        }}>{t("text.remove")}</Button>
                                </Space>
                            }>
                                <MoreOutlined />
                            </Popover>
                        </Space>
                    )}
                </>
            }>
            <Descriptions bordered column={1} labelStyle={{ width: "100px" }}>
                <Descriptions.Item label={t("text.cate")}>
                    {props.reviewInfo.review_type == REVIEW_TYPE_CODE && t("project.review.cate.code")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_FLOW && t("project.review.cate.flow")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_PRODUCT && t("project.review.cate.product")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_BUG && t("project.review.cate.bug")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_TEST && t("project.review.cate.test")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_MONTH && t("project.review.cate.month")}
                    {props.reviewInfo.review_type == REVIEW_TYPE_QUARTER && t("project.review.cate.quarter")}
                </Descriptions.Item>
                <Descriptions.Item label={t("project.review.releateMember")}>
                    <Space style={{ flexWrap: "wrap" }}>
                        {props.reviewInfo.member_list.map(memberItem => (
                            <Space key={memberItem.member_user_id} style={{ backgroundColor: "#eee", padding: "2px 10px", borderRadius: "6px" }}>
                                <UserPhoto logoUri={memberItem.member_logo_uri} style={{ width: "20px", borderRadius: "10px" }} />
                                {memberItem.member_display_name}
                            </Space>
                        ))}
                    </Space>
                </Descriptions.Item>
                <Descriptions.Item label={t("text.desc")}>
                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word", paddingLeft: "10px" }}>{props.reviewInfo.desc}</pre>
                </Descriptions.Item>
                <Descriptions.Item label={t("project.review.createTime")}>
                    {moment(props.reviewInfo.create_time).format("YYYY-MM-DD HH:mm")}
                </Descriptions.Item>
            </Descriptions>

            {showUpdateModal == true && projectStore.curProject !== undefined && (
                <EditReviewModal reviewInfo={props.reviewInfo} projectInfo={projectStore.curProject}
                    memberList={memberStore.memberList.map(item => item.member)} onClose={() => setShowUpdateModal(false)} />
            )}
            {showRemoveModal == true && (
                <Modal open title={t("project.review.remove")} mask={false}
                    okText={t("text.remove")} okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowRemoveModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeReview();
                    }}>
                    {t("project.review.removeMsg", { name: props.reviewInfo.title })}
                </Modal>
            )}
        </Card>
    );
});

const PAGE_SIZE = 10;

const ReviewList = () => {
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');

    const [reviewList, setReviewList] = useState<SimpleReviewInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);

    const loadReviewList = async (page: number) => {
        const res = await request(list_simple_review({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            filter_by_review_type: projectStore.filterReviewByType != null,
            review_type: projectStore.filterReviewByType ?? REVIEW_TYPE_CODE,
            filter_by_title_keyword: projectStore.filterReviewByTitleKeyword != "",
            title_keyword: projectStore.filterReviewByTitleKeyword,
            offset: page * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setReviewList(res.review_list);
    };

    const onUpdate = async (reviewId: string) => {
        const res = await request(get_review({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            review_id: reviewId,
        }));
        setReviewList(oldList => {
            const index = oldList.findIndex(item => item.review_id == reviewId);
            if (index != -1) {
                oldList[index] = res.review;
            }
            return oldList.slice();
        });
    }

    useEffect(() => {
        if (projectStore.curProjectId != "") {
            loadReviewList(projectStore.curReviewPage);
        }
    }, [projectStore.curProjectId, projectStore.curReviewPage, projectStore.filterReviewByType, projectStore.filterReviewByTitleKeyword]);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ProjectNotice?.CreateReviewNotice !== undefined && notice.ProjectNotice.CreateReviewNotice.project_id == projectStore.curProjectId) {
                projectStore.curReviewPage = 0;
                loadReviewList(0);
            } else if (notice.ProjectNotice?.UpdateReviewNotice !== undefined && notice.ProjectNotice.UpdateReviewNotice.project_id == projectStore.curProjectId) {
                onUpdate(notice.ProjectNotice.UpdateReviewNotice.review_id);
            } else if (notice.ProjectNotice?.RemoveReviewNotice !== undefined && notice.ProjectNotice.RemoveReviewNotice.project_id == projectStore.curProjectId) {
                const reviewId = notice.ProjectNotice.RemoveReviewNotice.review_id;
                setReviewList(oldList => {
                    const tmpList = oldList.filter(item => item.review_id != reviewId);
                    return tmpList;
                });
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <List rowKey="review_id" dataSource={reviewList}
            pagination={{ current: projectStore.curReviewPage + 1, total: totalCount, pageSize: PAGE_SIZE, onChange: page => projectStore.curReviewPage = (page - 1), hideOnSinglePage: true, showSizeChanger: false }}
            renderItem={reviewItem => (
                <List.Item>
                    <ReviewCard reviewInfo={reviewItem} />
                </List.Item>
            )} />
    );
};

export default observer(ReviewList);